package com.example.sys.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.config.ResponseBean;
import com.example.config.UnicomResponseEnums;
import com.example.sys.entity.DictData;
import com.example.sys.service.DictDataService;
import com.example.sys.vo.DictDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典数据表 前端控制器
 * </p>
 *
 * @author anan
 * @since 2019-06-20
 */
@RestController
@RequestMapping("/sys/dict-data")
public class DictDataController {

    @Autowired
    private DictDataService dictDataService;

    @GetMapping("/getDictDataList")
    public ResponseBean<UnicomResponseEnums> getDictDataList(DictDataVo dictDataVo){
        System.out.println(dictDataVo);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(dictDataVo, false, true);
        if (stringObjectMap.isEmpty()){
            List<DictData> dictTypes=dictDataService.list();
            return new ResponseBean(true, dictTypes, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(true, dictDataService.selectPage(dictDataVo), UnicomResponseEnums.SUCCESS_OPTION);
    }

    @PostMapping("/addDictData")
    public ResponseBean<UnicomResponseEnums> addDictData(@RequestBody @Valid DictData dictData){
        if (!dictData.toString().isEmpty()) {
            dictDataService.save(dictData);
            return new ResponseBean(true, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(false, UnicomResponseEnums.OPERATION_FAILED);
    }

    @PostMapping("/updateDictDataByDictCode")
    public ResponseBean<UnicomResponseEnums> updateDictDataByDictCode(@RequestBody @Valid DictData dictData){
        UpdateWrapper<DictData> wrapper = new UpdateWrapper<>();
        wrapper.eq("dict_code", dictData.getDictCode());
        if (dictDataService.update(dictData,wrapper)){
            return new ResponseBean(true,UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(true, UnicomResponseEnums.OPERATION_FAILED);
    }

    @DeleteMapping("/deleteByDictCode")
    public ResponseBean<UnicomResponseEnums> deleteByDictCode(@RequestBody DictDataVo dictDataVo){
        QueryWrapper<DictData> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictDataVo.getDictCode());
        if (dictDataService.remove(wrapper)){
            return new ResponseBean(true,UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(true, UnicomResponseEnums.OPERATION_FAILED);
    }

}
